using System;
using System.Diagnostics;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Specialized;
using System.Web.Services;
using System.Web;
using System.Text.RegularExpressions;
using LtMbs.CrmSdkHelperClass;
using CrmServiceWebReference;
using System.Xml;
using KalDev;
using Resources;
namespace LtMbs
{
    /// <summary>
    /// Summary description for Common
    /// </summary>
    public class Common
    {
        /// <summary>
        /// Common methods used throught all classes
        /// </summary>
        internal Common()
        { }
        /// <summary>
        /// Removes the HTML tags.
        /// Removes comments
        /// Removes DOCTYPE's
        /// Configured from the resources files, so if there is any HTML tags that slips through you can add it in the resource file
        /// </summary>
        /// <param name="input">The input.</param>
        /// <returns></returns>
        public static string removeHTMLTags(string input)
        {
            return Regex.Replace(input, "<(.|\n)*?>", "");
        }
        /// <summary>
        /// Creates the Authorizations header for the KMS Search Service.
        /// This has been changed, and no longer require the password, but it does require
        /// the 
        /// </summary>
        /// <returns></returns>
        public static AuthHeader CreateAuthorizationHeader()
        {
            AuthHeader header = new AuthHeader();
            header.Username = ConfigurationManager.AppSettings["KalHeader.Username"];
            header.Password = ConfigurationManager.AppSettings["KalHeader.Password"];
            return header;
        }
        /// <summary>
        /// Creates the security and configuring the credentials for use with the KMS web services
        /// </summary>
        /// <remarks>
        /// Set a timeout value based on a setting in the resource file
        /// Sets UnsafeAuthenticatedConnectionSharing =true
        /// </remarks>
        /// <returns></returns>
        public static CRMService KmsAuthorize()
        {
            CRMService service = new CRMService();

            service.Credentials = Credential();

            service.AuthHeaderValue = CreateAuthorizationHeader();
            service.UnsafeAuthenticatedConnectionSharing = true;
            service.Timeout = int.Parse(Resource.WebServiceTimeOut);
            return service;
        }
        /// <summary>
        /// Write exceptions to the event logs
        /// </summary>
        public static void LogErrorMessage(Exception errorHandler)
        {
            try
            {

                // Create the source, if it does not already exist.
                if (!EventLog.SourceExists("WrapperSearchService"))
                {
                    //An event log source should not be created and immediately used.
                    //There is a latency time to enable the source, it should be created
                    //prior to executing the application that uses the source.
                    //Execute this sample a second time to use the new source.
                    EventLog.CreateEventSource("WrapperSearchService", "Application");
                }

                // Create an EventLog instance and assign its source.
                EventLog myLog = new EventLog();
                myLog.Source = "WrapperSearchService";
                myLog.WriteEntry(errorHandler.InnerException.Data.ToString(), EventLogEntryType.Error);
            }
            catch { }
        }
        /// <summary>
        /// Creates the crm service
        /// </summary>
        /// <returns></returns>
        public static CrmServiceWebReference.CrmService CrmAutorize()
        {
            CrmServiceWebReference.CrmService service = new CrmServiceWebReference.CrmService();

            service.Credentials = Credential();
            
            service.UnsafeAuthenticatedConnectionSharing = true;
            service.Timeout = int.Parse(Resource.WebServiceTimeOut);
            
            return service;
        }
        /// <summary>
        /// Creates credentials based on settings in the web.config
        /// </summary>
        /// <returns></returns>
        private static System.Net.NetworkCredential Credential()
        {
            System.Net.NetworkCredential credential = new System.Net.NetworkCredential();

            if (ConfigurationManager.AppSettings[Resource.AppSettingsUseIntegratedAuthentication].ToLower().Contains("true"))
            {
                credential = (System.Net.NetworkCredential)System.Net.CredentialCache.DefaultNetworkCredentials;
            }
            else
            { 
                 string userName = ConfigurationManager.AppSettings[Resource.AppSettingsKalDevUserName];
                string password = ConfigurationManager.AppSettings[Resource.AppSettingsKalDevPassword];
                string domain = ConfigurationManager.AppSettings[Resource.AppSettingsKalDevDomain];

                credential = new System.Net.NetworkCredential(userName, password, domain);
            }

            return credential;
        }
        /// <summary>
        /// Returns the users work in progress queue, based on credentials
        /// </summary>
        /// <returns></returns>
        public static queue wipQueue()
        {
            WhoAmIRequest userRequest = new WhoAmIRequest();
            WhoAmIResponse respons = new WhoAmIResponse();
            WhoAmIResponse user = (WhoAmIResponse)CrmAutorize().Execute(userRequest);

            QueryByAttribute query = new QueryByAttribute();
            query.ColumnSet = new AllColumns();
            query.EntityName = EntityName.queue.ToString();
            query.Attributes = new string[] { "primaryuserid", "queuetypecode" };
            query.Values = new string[] { user.UserId.ToString(), "3" };
            BusinessEntityCollection results = CrmAutorize().RetrieveMultiple(query);
            return (queue)results.BusinessEntities[0];
        }

        /// <summary>
        /// Gets the full path and file name to the configuration file, that drives the site,
        /// uses the appDomainAppPath, and Resource.ConfigurationFile
        /// </summary>
        /// <returns></returns>
        private static string configurationFilePath()
        {
            string baseDir = System.Web.HttpRuntime.AppDomainAppPath;
            string configPath = Resource.ConfigurationFile;
            return string.Concat(baseDir, configPath);
        }
        /// <summary>
        /// Updates the config file.
        /// </summary>
        /// <param name="dateTime">The date time.</param>
        public static void updateConfigFile(string dateTime)
        {
            string configurationFile = configurationFilePath();
            //update the config file
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(configurationFile);
            XmlNode node = xmldoc.DocumentElement.SelectSingleNode("//appSettings//add[@key='lastFeedbackRunDate']");

            if (!string.IsNullOrEmpty(node.Attributes[1].Value))
            {
                node.Attributes[1].Value = dateTime;
                xmldoc.Save(configurationFile);
            }

            //update the cached setting
            dateTime = dateTime - TimeSpan.FromHours(1);

            System.Configuration.ConfigurationManager.AppSettings.Set("lastFeedbackRunDate", dateTime);
        }

    }
}